package com.itheima.web;

import com.itheima.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    //从yml文件中取出uploadPath
    @Value("${uploadPath}")
    String uploadPath;

    /**
     * 把指定的图片保存在指定的文件夹中以便下载使用
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {

        String oldName = file.getOriginalFilename();

        String uu = UUID.randomUUID().toString();

        String s = oldName.substring(oldName.lastIndexOf("."));

        String newName = uu + s;

        File directory = new File(uploadPath);

        if (!directory.exists()) {

            directory.mkdirs();

        }

        File targetFile = new File(directory, newName);

        file.transferTo(targetFile);

        return R.success(newName);

    }

    /**
     * 从指定的文件夹中下载到当前页面
     * @param name
     * @param response
     * @throws IOException
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {

        File file = new File(uploadPath, name);

        FileInputStream fis = new FileInputStream(file);

        byte[] bye = new byte[8192];

        int len = 0;

        while ((len = fis.read(bye)) != -1) {

            response.getOutputStream().write(bye, 0, len);

        }

        fis.close();

    }

}
